<?php
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller 
{

    /*登录页面*/
    public function index()
    {
        $code = $_GET['code'];//获取code
        if($code){      
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxe15c975a8af231c4&secret=97388e017467b6f8990e3cac66339034&code='.$code.'&grant_type=authorization_code';
            $weixin =  file_get_contents($url);//通过code换取网页授权access_token
            $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
            $array = get_object_vars($jsondecode);//转换成数组
            $openid = $array['openid'];//输出openid

            $userModel    = M('user');
            $use['openid'] = $openid;
            $res          = $userModel->where($use)->limit(1)->select();

            if($res)
            {
                $this->success('您已登录！', __APP__.'/Admin/Index/index');
                session('user_id',$res['0']['user_id']);
            }else
            {
                $this->success('您还未登录！', __APP__.'/Admin/Login/index');
            }
        }
       $this->assign('openid', $openid);
       $this->display();
    }

    /*登录*/
    public function signIn()
    {
        $arr['phone'] = trim(I('post.phone'));
        $arr['pwd']   = md5(I('post.pwd'));

        $UserModer    = D('User');
        $res          = $UserModer->checkUse($arr['phone'], $arr['pwd']);

        if($res)
        {
            $this->success('登录成功！', __APP__.'/Admin/Index/index');

            $UserModer->points($res['0']['user_id']);
            session('user_id',$res['0']['user_id']);
        }else
        {
            $this -> error('输入的电话号码或密码不正确，请重新输入');
        }
    }

    /*注册*/
    public function register()
    {
        $this->display();
    }

    public function registerIn()
    {
        $use['phone'] = trim(I('post.phone'));
        $use['pwd']   = md5(I('post.pwd'));
        
        $UserModer    = D('User');
        $res          = $UserModer->insertUse($use['phone'], $use['pwd']);

        if ($res)
        {
            $this->success('注册成功，可以进行登录！','index');
            
        }elseif ($res == 0)
        {
            $this -> error('输入的电话号码已被注册</br>或者您填写的电话号码格式不正确', 'register');
            
            
        }
    }
}

